package du.myseckill.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import du.myseckill.dao.GoodsDao;
import du.myseckill.dto.SecKillMsg;
import du.myseckill.dto.SeckillExcecution;
import du.myseckill.enums.SecKillStatEnum;
import du.myseckill.exception.ServerException;
import du.myseckill.pojo.Goods;
import du.myseckill.service.GoodsService;
import du.myseckill.vo.SecKillResult;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.util.Date;

/**
 * 消费者，消费消息队列中的秒杀操作消息
 */
@Component
@RabbitListener(queues = {"secKill_queue"})
public class SecKillMQConsumer {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsService goodsService;

    @RabbitHandler
    public void secKillConsumer(String msg, Channel channel,
                                @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws ServerException, IOException {
        try {
            SecKillMsg secKillMsg = JSON.parseObject(msg, SecKillMsg.class);
            //执行秒杀
            SeckillExcecution seckillExcecution = goodsService.executeSecKillDBPLock(secKillMsg.getGoodsId(), secKillMsg.getUserId(), secKillMsg.getUserPhone(), secKillMsg.getMd5());
            //利用websocket将秒杀结果返回给用户
            WebSocketServer.sendInfo(new SecKillResult<>(true,seckillExcecution), secKillMsg.getUserId().toString());
            channel.basicAck(tag,false);
        }catch (Exception e){
            channel.basicNack(tag,false,false);
            e.printStackTrace();

        }
    }
}
